package com.jjc.android.activity

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.os.Bundle
import android.view.View
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.TextView
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.jjc.android.*
import com.jjc.android.base.BaseActivity
import com.jjc.android.dialog.MessageImageDialog
import com.jjc.android.entity.DetectionInfo
import com.jjc.android.util.messenger.ActivityMessenger
import com.jjc.android.view.AutoFitTextView
import com.king.zxing.ViewfinderView
import com.otaliastudios.cameraview.CameraLogger
import com.otaliastudios.cameraview.CameraView
import com.otaliastudios.cameraview.size.SizeSelector
import com.otaliastudios.cameraview.size.SizeSelectors
import com.hjq.permissions.OnPermissionCallback
import com.hjq.toast.ToastUtils

class CameraActivity : BaseActivity(), View.OnClickListener{

    companion object {
        private val LOG = CameraLogger.create("DemoApp")

        fun start(context:Activity,detectionInfo: DetectionInfo? = null,action:((String?)->Unit)? = null){
            if(XXPermissions.isGranted(context, Permission.CAMERA,Permission.WRITE_EXTERNAL_STORAGE,Permission.READ_EXTERNAL_STORAGE)){
                realStart(context,detectionInfo,action)
            }else{
                XXPermissions.with(context)
                    .permission(Permission.CAMERA,Permission.WRITE_EXTERNAL_STORAGE,Permission.READ_EXTERNAL_STORAGE)
                    .request(object : OnPermissionCallback{
                        override fun onGranted(
                            permissions: MutableList<String>,
                            allGranted: Boolean
                        ) {
                            realStart(context,detectionInfo,action)
                        }

                        override fun onDenied(
                            permissions: MutableList<String>,
                            doNotAskAgain: Boolean
                        ) {
                            ToastUtils.show(context.getString(R.string.permission_fail_txt))
                        }
                    })
            }
        }

        private fun realStart(context:Activity,detectionInfo: DetectionInfo?,action:((String?)->Unit)?){
            val intent = Intent(context,CameraActivity::class.java)
            intent.putExtra(Constants.BUNDLE_INFO,detectionInfo)
            ActivityMessenger.startActivityForResult(context,intent){
                it?.getStringExtra(Constants.BUNDLE_INFO)?.let {id->
                    if(id=="-1"){
                        action?.invoke(null)
                    }else{
                        action?.invoke(id)
                    }
                }

            }
        }

    }

    private val camera: CameraView by lazy { findViewById(R.id.camera) }
    private val okBtn: TextView by lazy { findViewById<TextView>(R.id.okBtn) }
    private val capturePicture: ImageButton by lazy { findViewById<ImageButton>(R.id.capturePicture) }
    private val tvDebugmsg: AutoFitTextView by lazy { findViewById<AutoFitTextView>(R.id.tv_debugmsg) }
    private val maskLableLayout: LinearLayout by lazy { findViewById<LinearLayout>(R.id.maskLableLayout) }
    private val viewfinderView: ViewfinderView by lazy { findViewById<ViewfinderView>(R.id.viewfinderView) }

    override val layoutId: Int = R.layout.activity_camera
    private lateinit var imageAnalysisManager: ImageAnalysisManager
    private lateinit var detectionInfo: DetectionInfo

    override fun initView(savedInstanceState: Bundle?) {
        CameraLogger.setLogLevel(CameraLogger.LEVEL_INFO)
//        camera.setPreviewStreamSize(SizeSelectors.smallest())
        camera.setLifecycleOwner(this)
        camera.open()
        tvDebugmsg.visibility = if(GlobalManager.isShowDebugInfo) View.VISIBLE else View.GONE
        imageAnalysisManager = ImageAnalysisManager(this,detectionInfo,camera,tvDebugmsg)
        imageAnalysisManager.setFinishCallback {
            runOnUiThread {
                capturePicture.visibility = View.VISIBLE
            }
        }
        capturePicture.setOnClickListener(this)
        okBtn.setOnClickListener(this)
    }


    override fun setupArguments(args: Bundle?) {
        detectionInfo = (args?.getSerializable(Constants.BUNDLE_INFO) as? DetectionInfo)?:DetectionInfo()
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.capturePicture -> capturePicture()
            R.id.okBtn -> {
                okBtn.visibility = View.GONE
                maskLableLayout.visibility = View.GONE
                viewfinderView.visibility = View.GONE
                capturePicture.visibility = View.GONE
                if (camera.isTakingPicture) return
                imageAnalysisManager.adjustCameraParam()
            }
        }
    }

    override fun isStatusWhiteModel(): Boolean {
        return true
    }

    private fun capturePicture() {
        if (camera.isTakingPicture) return
        capturePicture.visibility = View.GONE
        imageAnalysisManager.takePicture()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String?>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        val valid = grantResults.all { it == PERMISSION_GRANTED }
        if (valid && !camera.isOpened) {
            camera.open()
        }
    }
}
